//
//  InitDataRequset.m
//  HengHuaSupervision
//
//  Created by XD-XY on 3/27/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "InitDataRequset.h"
#import "XDHeader.h"
#import "XDTools.h"
#import "Request.h"
#import "Response.h"
#import "MyFile.h"
#import "JSONKit.h"
#import "FMDB.h"

@implementation InitDataRequset

//初始化它自身的全局变量
-(void)initInitDataRequsetDict
{
    dataDict = [[NSMutableDictionary alloc] init];
    statusDict = [[NSMutableDictionary alloc] init];
}

//获取标签信息
-(void)getTagsInfomation:(NSString *)currentTime
{
    Request * tagsRequest = [[Request alloc] init];
//   NSDictionary* requestEntity = [@"{\"udid\":\"123456\"}" objectFromJSONString];
        NSDictionary* requestEntity;
    if (!currentTime){
        requestEntity =nil;
    }else{
         NSString * str = [NSString stringWithFormat:@"{\"currentTime\":\"%@\"}",currentTime];
        requestEntity =[str objectFromJSONString];
    }

    [tagsRequest request:mTrace_GettagsUrl keyValue:requestEntity completionHandler:^(ResponseData *data) {
        if([data.result intValue]==1){
            [[NSUserDefaults standardUserDefaults] setValue:data.currentTime forKey:mTagsCurrentTime];
            [dataDict setValue:data.responseJson forKey:mTrace_GettagsUrl];
            [statusDict setValue:@"1" forKey:mTrace_GettagsUrl];
 
        }else{
            [statusDict setValue:@"-1" forKey:mTrace_GettagsUrl];
            DDLOG(@"获取标签信息：%@",data.errorMsg);
        }
        [self insertDataToDB:dataDict andAllStatus:statusDict];
    }];
}

//获取资产信息
-(void)getPropertyInfomation:(NSString *)currentTime
{
    Request * propertyRequest = [[Request alloc] init];
    NSString * str;
    if (!currentTime){
        str = [NSString stringWithFormat:@"{\"project_id\":\"%@\"}",[UserInfo sharedUserInfo].project_id];
    }else{
        str = [NSString stringWithFormat:@"{\"project_id\":\"%@\",\"currentTime\":\"%@\"}",[UserInfo sharedUserInfo].project_id,currentTime];
    }
    NSDictionary * requestEntity = [str objectFromJSONString];
//    NSDictionary* requestEntity =nil;
    [propertyRequest request:mTrace_GetpropertydatasUrl keyValue:requestEntity completionHandler:^(ResponseData *data) {
        if([data.result intValue]==1){
            [[NSUserDefaults standardUserDefaults] setValue:data.currentTime forKey:mPropertyCurrentTime];
            [dataDict setValue:data.responseJson forKey:mTrace_GetpropertydatasUrl];
            [statusDict setValue:@"1" forKey:mTrace_GetpropertydatasUrl];
 
        }else{
            [statusDict setValue:@"-1" forKey:mTrace_GetpropertydatasUrl];
            DDLOG(@"获取资产信息：%@",data.errorMsg);
        }
        [self insertDataToDB:dataDict andAllStatus:statusDict];
    }];
}

//获取资产标签关联信息
-(void)getPropertyWithLabelInfomation:(NSString *)currentTime
{
    Request * propertyWithlabelRequest = [[Request alloc] init];
    NSString * str;
    if (!currentTime){
        str = [NSString stringWithFormat:@"{\"project_id\":\"%@\"}",[UserInfo sharedUserInfo].project_id];
    }else{
        str = [NSString stringWithFormat:@"{\"project_id\":\"%@\",\"currentTime\":\"%@\"}",[UserInfo sharedUserInfo].project_id,currentTime];
    }
    NSDictionary * requestEntity = [str objectFromJSONString];
//    NSDictionary* requestEntity =nil;
    [propertyWithlabelRequest request:mTrace_GetpropertywithlabeldatasUrl keyValue:requestEntity completionHandler:^(ResponseData *data) {
        if([data.result intValue]==1){
            [[NSUserDefaults standardUserDefaults] setValue:data.currentTime forKey:mPropertyWithLabelCurrentTime];
            [dataDict setValue:data.responseJson forKey:mTrace_GetpropertywithlabeldatasUrl];
            [statusDict setValue:@"1" forKey:mTrace_GetpropertywithlabeldatasUrl];
        }else{
            [statusDict setValue:@"-1" forKey:mTrace_GetpropertywithlabeldatasUrl];
            DDLOG(@"获取资产标签关联信息：%@",data.errorMsg);
        }
        [self insertDataToDB:dataDict andAllStatus:statusDict];
    }];

}

//获取扫描记录
-(void)getScanInfomation:(NSString *)currentTime
{
    Request * scanRequest = [[Request alloc] init];
    NSString * str;
    if (!currentTime){
        str = [NSString stringWithFormat:@"{\"project_id\":\"%@\"}",[UserInfo sharedUserInfo].project_id];
    }else{
        str = [NSString stringWithFormat:@"{\"project_id\":\"%@\",\"currentTime\":\"%@\"}",[UserInfo sharedUserInfo].project_id,currentTime];
    }
    NSDictionary * requestEntity = [str objectFromJSONString];
//       NSDictionary* requestEntity =nil;
    [scanRequest request:mTrace_Getscandatas keyValue:requestEntity completionHandler:^(ResponseData *data) {
        if([data.result intValue]==1){
            [[NSUserDefaults standardUserDefaults] setValue:data.currentTime forKey:mScanCurrentTime];
            [dataDict setValue:data.responseJson forKey:mTrace_Getscandatas];
            [statusDict setValue:@"1" forKey:mTrace_Getscandatas];

        }else{
            [statusDict setValue:@"-1" forKey:mTrace_Getscandatas];
            DDLOG(@"获取扫描记录信息：%@",data.errorMsg);
        }
        [self insertDataToDB:dataDict andAllStatus:statusDict];
    }];
}

//获取监造信息
-(void)getSupervisionInfomation:(NSString *)currentTime
{
    Request * supervisionRequest = [[Request alloc] init];
    NSString * str;
    if (!currentTime){
        str = [NSString stringWithFormat:@"{\"project_id\":\"%@\"}",[UserInfo sharedUserInfo].project_id];
    }else{
        str = [NSString stringWithFormat:@"{\"project_id\":\"%@\",\"currentTime\":\"%@\"}",[UserInfo sharedUserInfo].project_id,currentTime];
    }
    NSDictionary * requestEntity = [str objectFromJSONString];
    //       NSDictionary* requestEntity =nil;
    DDLOG(@"===============%@================",str);
    [supervisionRequest request:mTrace_Getsupervision keyValue:requestEntity completionHandler:^(ResponseData *data) {
        if([data.result intValue]==1){
            [[NSUserDefaults standardUserDefaults] setValue:data.currentTime forKey:mSupervisionCurrentTime];
            [dataDict setValue:data.responseJson forKey:mTrace_Getsupervision];
            [statusDict setValue:@"1" forKey:mTrace_Getsupervision];

        }else{
            [statusDict setValue:@"-1" forKey:mTrace_Getsupervision];
            DDLOG(@"获取扫描记录信息：%@",data.errorMsg);
        }
        [self insertDataToDB:dataDict andAllStatus:statusDict];
    }];
}


//将数据插入到数据库
-(void)insertDataToDB:(NSMutableDictionary *)respose andAllStatus:(NSMutableDictionary *)status
{
    //全部下载
    if ([[status valueForKey:mTrace_GettagsUrl] intValue]==1&&
        [[status valueForKey:mTrace_GetpropertydatasUrl] intValue]==1&&
        [[status valueForKey:mTrace_GetpropertywithlabeldatasUrl] intValue]==1&&
        [[status valueForKey:mTrace_Getscandatas] intValue]==1&&
        [[status valueForKey:mTrace_Getsupervision] intValue]==1){
    
        //标签库信息
        NSDictionary * tagsDic = [XDTools JSonFromString:[respose valueForKey:mTrace_GettagsUrl]];
        NSArray * tagsArray = [tagsDic valueForKey:CONTENT];
        
        //资产信息
        NSDictionary * propertyDic = [XDTools JSonFromString:[respose valueForKey:mTrace_GetpropertydatasUrl]];
        NSArray * propertyArray = [propertyDic valueForKey:CONTENT];
        
        //资产关联标签信息
        NSDictionary * propertyWithLabelDic = [XDTools JSonFromString:[respose valueForKey:mTrace_GetpropertywithlabeldatasUrl]];
        NSArray * propertyWithLabelArray = [propertyWithLabelDic valueForKey:CONTENT];
        
        //扫描记录信息
        NSDictionary * scanDic = [XDTools JSonFromString:[respose valueForKey:mTrace_Getscandatas]];
        NSArray * scanArray = [scanDic valueForKey:CONTENT];
        
        //监造信息（贴标签信息）
        NSDictionary * supervisionDic = [XDTools JSonFromString:[respose valueForKey:mTrace_Getsupervision]];
        NSArray * supervisionArray = [supervisionDic valueForKey:CONTENT];
        
        NSString * aPath = [XDTools databaseFilePath];
        DDLOG(@"aPth = %@",aPath);
        NSArray * deleteArray = [self setDeleteArray];
        //用fmdb的事务队列存储数据
        FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
        [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
            if (![XDTools sharedXDTools].isReflash){
                //全部下载
                for(int i=0;i<[deleteArray count];i++){
                    BOOL a = [db executeUpdate:[deleteArray objectAtIndex:i]];
                    if (!a){
                        *rollback =YES;
                        return;
                    }
                }
            }
                        
            for (NSDictionary * dic in tagsArray){
                TagsItem * item = [[TagsItem alloc] initWithDictionary:dic];
                BOOL a = [db executeUpdate:@"INSERT INTO T_TRACE_TAGS VALUES(?,?,?)",item.code,item.notes,item.version];
                if (!a){
                    * rollback =YES;
                    return;
                }
            }
            
            for (NSDictionary * dic in propertyArray){
                PropertyItem * item = [[PropertyItem alloc] initWithDictionary:dic];
                BOOL a = [db executeUpdate:@"INSERT INTO T_TRACE_ASSERTS VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",item.propertyid,item.name,item.code,item.model,item.type,item.factory_name,item.factory_code,item.factory_addr,item.factory_linkman,item.factory_phone,item.supervision_unitname,item.supervision_unitcode,item.supervision_mode,item.supervision_linkman,item.version,item.status,item.project_id];
                if (!a){
                    * rollback =YES;
                    return;
                }
                
            }
            
            for (NSDictionary * dic in propertyWithLabelArray){
                NSString * assert_id = [NSString stringWithFormat:@"%@",[dic valueForKey:@"assert_id"]];
                for (NSDictionary * dicc in [dic valueForKey:@"data"]){
                    PropertywithlabelItem * item = [[PropertywithlabelItem alloc] initWithDictionary:dicc];
                    item.assert_id = assert_id;
                    
                    if ([XDTools sharedXDTools].isReflash){
                        //增量下载
                        BOOL aa = [db executeUpdate:@"DELETE FROM T_TRACE_ASSERTS_TAG WHERE id =?",item.record_id];
                        if (!aa){
                            * rollback =YES;
                            return;
                        }
                    }
                    
                    BOOL a = [db executeUpdate:@"INSERT INTO T_TRACE_ASSERTS_TAG VALUES(?,?,?,?,?)",item.record_id,item.assert_id,item.tag_code,item.part,item.create_time];
                    if (!a){
                        * rollback =YES;
                        return;
                    }
                }
                
            }
            
            for (NSDictionary * dic in scanArray){
                NSString * assert_id = [NSString stringWithFormat:@"%@",[dic valueForKey:@"assert_id"]];
                for (NSDictionary * dicc in [dic valueForKey:@"data"]){
                    ScanItem * item = [[ScanItem alloc] initWithDictionary:dicc];
                    item.assert_id = assert_id;
                    
                    
                    NSArray * brArray = [[dicc valueForKey:@"photos"] valueForKey:@"breviaryphotos"];
                    NSMutableString * brString = [[NSMutableString alloc] init];
                    for (int i=0;i<[brArray count];i++){
                        if (i<[brArray count]-1){
                            [brString appendString:[NSString stringWithFormat:@"%@,",[brArray objectAtIndex:i]]];
                        }else{
                            [brString appendString:[brArray objectAtIndex:i]];
                        }
                    }
                    
                    NSArray * phArray = [[dicc valueForKey:@"photos"] valueForKey:@"photphotos"];
                    NSMutableString * phString = [[NSMutableString alloc] init];
                    for (int i=0;i<[phArray count];i++){
                        if (i<[phArray count]-1){
                            [phString appendString:[NSString stringWithFormat:@"%@,",[phArray objectAtIndex:i]]];
                        }else{
                            [phString appendString:[phArray objectAtIndex:i]];
                        }
                    }
                    
                    item.breviaryphoto = brString;
                    item.photphoto =phString;

//                    NSString * string1 = [NSString stringWithFormat:@"%@",[[dicc valueForKey:@"photos"] valueForKey:@"breviaryphotos"]];
//                    NSString * tstr1 = [string1 stringByReplacingOccurrencesOfString:@"(" withString:@""];
//                    NSString * mstr1 = [tstr1 stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//                    NSString * fstr1 = [mstr1 stringByReplacingOccurrencesOfString:@"\"" withString:@""];
//                    item.breviaryphoto = [fstr1 stringByReplacingOccurrencesOfString:@")" withString:@""];
//                   // item.breviaryphoto = [NSString stringWithFormat:@"%@",[[dicc valueForKey:@"photos"] valueForKey:@"breviaryphotos"]];
//                    
//                    NSString * string2 = [NSString stringWithFormat:@"%@",[[dicc valueForKey:@"photos"] valueForKey:@"breviaryphotos"]];
//                    NSString * tstr2 = [string2 stringByReplacingOccurrencesOfString:@"(" withString:@""];
//                    NSString * mstr2 = [tstr2 stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//                    NSString * fstr2 = [mstr2 stringByReplacingOccurrencesOfString:@"\"" withString:@""];
//                    item.photphoto = [fstr2 stringByReplacingOccurrencesOfString:@")" withString:@""];

                    if ([XDTools sharedXDTools].isReflash){
                        //增量
                        BOOL aa = [db executeUpdate:@"DELETE FROM T_TRACE_SCAN_LOG WHERE id =?",item.record_id];
                        if (!aa){
                            * rollback =YES;
                            return;
                        }
                    }
                    
                    BOOL a = [db executeUpdate:@"INSERT INTO T_TRACE_SCAN_LOG VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",item.record_id,item.assert_id,item.tag_code,item.scan_time,item.scan_location_gps,item.scan_location,item.scan_device,item.scan_devicename,item.scan_userid,item.scan_username,item.status,item.breviaryphoto,item.photphoto];
                    if (!a){
                        * rollback =YES;
                        return;
                    }
                }
                
            }
            
            for (NSDictionary * dic in supervisionArray){
                SupervisionItem * item = [[SupervisionItem alloc] initWithDictionary:dic];
                
                if ([XDTools sharedXDTools].isReflash){
                    //增量
                    BOOL aa = [db executeUpdate:@"DELETE FROM T_TRACE_SUPERVISION WHERE id =?",item.record_id];
                    if (!aa){
                        * rollback =YES;
                        return;
                    }
                }
                
                BOOL a = [db executeUpdate:@"INSERT INTO T_TRACE_SUPERVISION VALUES(?,?,?)",item.record_id,item.assert_id,item.notes];
                if (!a){
                    * rollback =YES;
                    return;
                }
            }
            
        }];
        [_delegate reloadDataFromDB:self];
        
    }else if (
              ([[status valueForKey:mTrace_GettagsUrl] intValue]==-1)&&
              ([[status valueForKey:mTrace_GetpropertydatasUrl] intValue]==-1)&&
              ([[status valueForKey:mTrace_GetpropertywithlabeldatasUrl] intValue]==-1)&&
              ([[status valueForKey:mTrace_Getscandatas] intValue]==-1)&&
              ([[status valueForKey:mTrace_Getsupervision] intValue]==-1)
              ){
        [_delegate failInitRequest];
        DDLOG(@"请求失败");
    }
    else{
        DDLOG(@"由于其中某个请求失败导致数据插入失败,或者数据正在请求中..");
    }
}

-(NSArray *)setDeleteArray
{
    NSArray * array = @[@"DELETE FROM T_TRACE_TAGS",@"DELETE FROM T_TRACE_ASSERTS",@"DELETE FROM T_TRACE_ASSERTS_TAG",@"DELETE FROM T_TRACE_SCAN_LOG",@"DELETE FROM T_TRACE_SUPERVISION"];
    return array;
}

@end
